package com.example.myapplication.User;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.NetworkOnMainThreadException;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.myapplication.Data.UserData;
import com.example.myapplication.LoginRegister.LoginActivity;
import com.example.myapplication.R;
import com.example.myapplication.Tool.TimestampTool;
import com.example.myapplication.http.ResponseBody;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class EditUserMessageActivity extends AppCompatActivity {

    private EditText edtAccount;
    private EditText edtGender;
    private EditText edtIdNum;
    private EditText edtCollege;
    private EditText edtPhone;
    private EditText edtEmail;
    private EditText edtRealname;
    private EditText edtTime;
    private String account;
    private String gender;
    private Boolean gender1;
    private String idNum;
    private String college;
    private String phone;
    private String email;
    private String realname;
    private String time;
    private UserData userData;
    private Button btEdit;
    private ImageView ivMessageExit;
    private BottomSheetDialog bottomSheetDialog;
    private ImageView ivAvatar;
    private RelativeLayout tvAlbum;
    private RelativeLayout tvCamera;


    private final Gson gson = new Gson();
    //请求数据
    private int code;// 响应码
    private String msg;// 提示信息
    private Object data;// 实际数据

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_user_message);
        initView();

        btEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(EditUserMessageActivity.this);
                builder.setTitle("提示")
                        .setMessage("是否确认修改信息，修改信息后需要重新登录");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();// 关闭对话框
                        initData();
                        post();
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                AlertDialog dialog = builder.create();
                dialog.show();
            }
        });
        ivMessageExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        ivAvatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                View bottomSheetView = getLayoutInflater().inflate(R.layout.edit_picture, null);
                bottomSheetDialog.setContentView(bottomSheetView);
                tvAlbum = bottomSheetView.findViewById(R.id.tv_album);
                tvCamera = bottomSheetView.findViewById(R.id.tv_camera);
                Album();//相册按钮
                Camera();//照相按钮
                bottomSheetDialog.show();
            }
        });

    }
    private void Album(){
        tvAlbum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();//相册
            }
        });
    }
    private void Camera() {
        tvCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();//照相
            }
        });
    }
    private void initView() {
        userData = (UserData) getIntent().getSerializableExtra("userData");
        bottomSheetDialog = new BottomSheetDialog(this);//底部弹窗
        edtAccount = findViewById(R.id.edt_account);
        edtGender = findViewById(R.id.edt_gender);
        edtCollege = findViewById(R.id.edt_college);
        edtPhone = findViewById(R.id.edt_phone);
        edtEmail = findViewById(R.id.edt_email);
        edtRealname = findViewById(R.id.edt_realname);
        edtTime = findViewById(R.id.edt_time);
        edtIdNum = findViewById(R.id.edt_id_number);
        btEdit = findViewById(R.id.bt_edit);
        ivMessageExit = findViewById(R.id.iv_message_exit);
        ivAvatar = findViewById(R.id.iv_avatar);

        edtAccount.setText(userData.getUserName());
        edtGender.setText(userData.getGender() ? "男" : "女");
        edtCollege.setText(userData.getCollegeName());
        edtPhone.setText(userData.getPhone());
        edtEmail.setText(userData.getEmail());
        edtRealname.setText(userData.getRealName());
        edtTime.setText(TimestampTool.timestampToDateTime(String.valueOf(userData.getInSchoolTime())));
        edtIdNum.setText(String.valueOf(userData.getIdNumber()));

    }

    private void initData(){
        account = edtAccount.getText().toString();
        gender = edtGender.getText().toString();
        gender1 = true;
        if(gender.equals("男")){
            gender1 = true;
        }else if(gender.equals("女")){
            gender1 = false;
        }
        college = edtCollege.getText().toString();
        phone = edtPhone.getText().toString();
        email = edtEmail.getText().toString();
        realname = edtRealname.getText().toString();
        time = edtTime.getText().toString();
        idNum = edtIdNum.getText().toString();
        Log.d("info1", String.valueOf(idNum));

    }
    private void post(){
        new Thread(() -> {

            // url路径
            String url = "http://47.107.52.7:88/member/sign/user/update";

            // 请求头
            Headers headers = new Headers.Builder()
                    .add("appId", "255cb403024d44f692620834ffc73623")
                    .add("appSecret", "12472e74638ef69e7412dbf2e818c2ae538d4")
                    .add("Accept", "application/json, text/plain, */*")
                    .build();

            // 请求体
            Map<String, Object> bodyMap = new HashMap<>();
            bodyMap.put("avatar", "https://guet-lab.oss-cn-hangzhou.aliyuncs.com/api/2023/09/23/62339bae-2574-45d0-bf5d-cf1a950b0681.jpeg");
            bodyMap.put("collegeName", college);
            bodyMap.put("email", email);
            bodyMap.put("gender", gender1);
            bodyMap.put("id", userData.getId());
            bodyMap.put("idNumber", idNum);
            bodyMap.put("inSchoolTime", time);
            bodyMap.put("phone", phone);
            bodyMap.put("realName", realname);
            bodyMap.put("userName", account);
            // 将Map转换为字符串类型加入请求体中

            String body = gson.toJson(bodyMap);

            MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");

            //请求组合创建
            Request request = new Request.Builder()
                    .url(url)
                    // 将请求头加至请求中
                    .headers(headers)
                    .post(RequestBody.create(MEDIA_TYPE_JSON, body))
                    .build();
            Log.d("info", String.valueOf(request));
            try {
                OkHttpClient client = new OkHttpClient();
                //发起请求，传入callback进行回调
                client.newCall(request).enqueue(callback);
            }catch (NetworkOnMainThreadException ex){
                ex.printStackTrace();
            }
        }).start();
    }

    /**
     * 回调
     */
    private final Callback callback = new Callback() {
        @Override
        public void onFailure(@NonNull Call call, IOException e) {
            //TODO 请求失败处理
            e.printStackTrace();
        }
        @Override
        public void onResponse(@NonNull Call call, Response response) throws IOException {
            //TODO 请求成功处理
            Type jsonType = new TypeToken<ResponseBody<Object>>(){}.getType();
            // 获取响应体的json串
            String body = response.body().string();
            Log.d("info", body);
            // 解析json串到自己封装的状态
            ResponseBody<Object> dataResponseBody = gson.fromJson(body,jsonType);
            Log.d("info", dataResponseBody.toString());

            // 获取响应的数据
            code = dataResponseBody.getCode();
            msg = dataResponseBody.getMsg();
            data = dataResponseBody.getData();

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    handleResponse();
                }
            });

        }
    };
    private void handleResponse(){
        if (code == 200) {
            Toast.makeText(EditUserMessageActivity.this, "修改成功", Toast.LENGTH_LONG).show();
            finish();
        }
        else {
            if (msg.equals("服务器内部错误")) {
                Toast.makeText(EditUserMessageActivity.this, "修改失败，请确实信息是否填写", Toast.LENGTH_LONG).show();
            } else if (msg != null){
                Toast.makeText(EditUserMessageActivity.this, msg, Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(EditUserMessageActivity.this, "修改失败", Toast.LENGTH_LONG).show();
            }
        }
    }

}